package com.interview.javabase.thread;

import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 生产者消费者
 * @author: zhangshuguang@vichain.com
 * @date: 2019/06/14 13:49
 */
public class Demo16 {

    public static void main(String[] args) throws InterruptedException {
        Share share = new Share();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.aPrint5();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.bPrint10();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.cPrint15();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

    }
}

class Share {

    private Integer number = 1;

    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void aPrint5() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                c1.await();
            }

            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName());
            }

            number = 2;
            c2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void bPrint10() throws InterruptedException {
        lock.lock();
        try {
            while (number != 2) {
                c2.await();
            }

            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName());
            }

            number = 3;
            c3.signal();
        }finally {
            lock.unlock();
        }

    }

    public void cPrint15() throws InterruptedException {
        lock.lock();
        try {
            while (number != 3) {
                c3.await();
            }

            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName());
            }

            number = 1;
            c1.signal();
        }finally {
            lock.unlock();
        }

    }
}